#include <iostream>
#include <random>
#include <dds/dds.h>
#include "start_atomic_0822_data_collection_service.h" // IDL生成的C语言头文件
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t publisher;
static dds_entity_t writer;

// 清理DDS资源
static void cleanup()
{
    if (writer != DDS_HANDLE_NIL)
        dds_delete(writer);
    if (publisher != DDS_HANDLE_NIL)
        dds_delete(publisher);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机导弹状态数据
start_atomic_0822_data_collection_service_DataCollectionInput generate_random_missile_state()
{
    // 静态随机数生成器（确保全局只初始化一次，提升性能）
    static std::mt19937 rng(std::random_device{}());

    // 为每个 int32_t 成员定义“合理取值范围”的均匀分布
    std::uniform_int_distribution<int32_t> device_id_dist(1, 1000);        // 设备ID（示例范围：1~1000）
    std::uniform_int_distribution<int32_t> collect_type_dist(0, 5);       // 采集类型（示例范围：0~5，可按实际枚举值调整）
    std::uniform_int_distribution<int32_t> sample_rate_dist(1, 10000);    // 采样率（示例范围：1~10000）
    std::uniform_int_distribution<int32_t> data_length_dist(100, 10000);  // 数据长度（示例范围：100~10000）
    std::uniform_int_distribution<int32_t> real_time_mode_dist(0, 1);     // 实时模式标记（示例：0=非实时，1=实时）

    // 初始化结构体并填充随机值
    start_atomic_0822_data_collection_service_DataCollectionInput data;
    data.device_id = device_id_dist(rng);
    data.collect_type = collect_type_dist(rng);
    data.sample_rate = sample_rate_dist(rng);
    data.data_length = data_length_dist(rng);
    data.real_time_mode = real_time_mode_dist(rng);

    return data;
}

int main()
{
    //初始化日志
    LogClient::getInstance().init("mock_0822_input_data_collection_service","mock_0822_input_data_collection_service");

    dds_return_t rc;

    // 1. 初始化DDS参与者（DomainParticipant）
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（Topic），名称需与订阅者一致
    topic = dds_create_topic(
        participant,
        &start_atomic_0822_data_collection_service_DataCollectionInput_desc, // IDL生成的类型描述
        "start_atomic_0822_data_collection_service",                      // 主题名称（必须与订阅者一致）
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建发布者（Publisher）
    publisher = dds_create_publisher(participant, NULL, NULL);
    if (publisher < 0)
    {
        std::cerr << "错误：创建发布者失败，原因：" << dds_strretcode(-publisher) << std::endl;
        LogClient::getInstance().logError("创建发布者失败，原因：" + std::string(dds_strretcode(-publisher)));
        cleanup();
        return EXIT_FAILURE;
    }

    dds_qos_t *qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    // 4. 创建数据写入器（DataWriter）
    writer = dds_create_writer(publisher, topic, qos, NULL);
    if (writer < 0)
    {
        std::cerr << "错误：创建写入器失败，原因：" << dds_strretcode(-writer) << std::endl;
        LogClient::getInstance().logError("创建写入器失败，原因：" + std::string(dds_strretcode(-writer)));
        cleanup();
        return EXIT_FAILURE;
    }
    dds_delete_qos(qos);

    std::cout << "DDS导弹状态发布者已启动，开始发送数据..." << std::endl;
    LogClient::getInstance().logInfo("DDS导弹状态发布者已启动，开始发送数据...");

    // 5. 循环发送数据（示例：发送10000次，每次间隔1秒）
    // for (int i = 0; i < 10000; i++)
    int i = 0;
    while (1)
    {
        // 生成随机导弹状态数据
        start_atomic_0822_data_collection_service_DataCollectionInput data = generate_random_missile_state();

        // 发送数据
        rc = dds_write(writer, &data);
        if (rc != DDS_RETCODE_OK)
        {
            std::cerr << "错误：dds_write失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_write失败，原因：" + std::string(dds_strretcode(-rc)));
            cleanup();
            return EXIT_FAILURE;
        }

        // 使用cout打印发送的信息
        std::string info = "已发送数据采集输入信息（第" + std::to_string(i + 1) + "次）：";
        info += "设备ID：" + std::to_string(data.device_id);
        info += "，采集类型：" + std::to_string(data.collect_type);
        info += "，采样率：" + std::to_string(data.sample_rate);
        info += "，数据长度：" + std::to_string(data.data_length);
        info += "，实时模式：" + std::to_string(data.real_time_mode);

        std::cout << "==============================" << std::endl;
        std::cout << info << std::endl;
        std::cout << "==============================" << std::endl;
        LogClient::getInstance().logInfo(info);

        // 间隔1秒发送
        i++;
        dds_sleepfor(DDS_SECS(1));
    }

    // 清理资源
    cleanup();
    return EXIT_SUCCESS;
}